import React, { useState, useEffect } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  Row, 
  Col, 
  Select, 
  InputNumber, 
  message, 
  Space, 
  Table, 
  Modal,
  Alert,
  Divider,
  Typography,
  Tooltip,
  Tag,
  Statistic
} from 'antd';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  CalculatorOutlined,
  SaveOutlined,
  EyeOutlined,
  CodeOutlined,
  ExperimentOutlined
} from '@ant-design/icons';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Paragraph } = Typography;

const CreateDerivedFactor = () => {
  const [form] = Form.useForm();
  const [selectedFactors, setSelectedFactors] = useState([]);
  const [isPreviewModalVisible, setIsPreviewModalVisible] = useState(false);
  const [derivedFactor, setDerivedFactor] = useState(null);

  // 模拟可用因子数据
  const availableFactors = [
    { id: 1, name: '动量因子', type: '技术因子', category: '技术分析', weight: 0.3, formula: 'momentum = (price_t - price_t-20) / price_t-20' },
    { id: 2, name: '价值因子', type: '基本面因子', category: '基本面', weight: 0.4, formula: 'value = (book_value / market_value)' },
    { id: 3, name: '规模因子', type: '风险因子', category: '风险控制', weight: 0.2, formula: 'size = log(market_cap)' },
    { id: 4, name: '质量因子', type: '基本面因子', category: '基本面', weight: 0.25, formula: 'quality = (roe * 0.4 + debt_to_equity * 0.3 + asset_turnover * 0.3)' },
    { id: 5, name: '波动率因子', type: '风险因子', category: '风险控制', weight: 0.15, formula: 'volatility = std(returns_60d)' },
    { id: 6, name: '成长因子', type: '基本面因子', category: '基本面', weight: 0.3, formula: 'growth = (revenue_growth * 0.5 + earnings_growth * 0.5)' },
    { id: 7, name: '流动性因子', type: '技术因子', category: '技术分析', weight: 0.2, formula: 'liquidity = log(turnover_rate * avg_volume)' },
    { id: 8, name: 'Beta因子', type: '风险因子', category: '风险控制', weight: 0.1, formula: 'beta = cov(returns, market_returns) / var(market_returns)' }
  ];

  const columns = [
    {
      title: '因子名称',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type) => <Tag color="blue">{type}</Tag>,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category) => <Tag color="green">{category}</Tag>,
    },
    {
      title: '权重',
      dataIndex: 'weight',
      key: 'weight',
      width: 100,
      render: (weight) => `${(weight * 100).toFixed(0)}%`,
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="查看公式">
            <Button 
              type="link" 
              size="small"
              icon={<EyeOutlined />}
              onClick={() => handleViewFormula(record)}
            />
          </Tooltip>
          <Tooltip title="移除">
            <Button 
              type="link" 
              size="small"
              danger
              icon={<DeleteOutlined />}
              onClick={() => handleRemoveFactor(record.id)}
            />
          </Tooltip>
        </Space>
      ),
    },
  ];

  const handleAddFactor = (factorId) => {
    const factor = availableFactors.find(f => f.id === factorId);
    if (factor) {
      const existingFactor = selectedFactors.find(f => f.id === factorId);
      if (existingFactor) {
        message.warning('该因子已添加');
        return;
      }
      
      const newFactor = {
        ...factor,
        customWeight: factor.weight // 默认使用原权重
      };
      setSelectedFactors([...selectedFactors, newFactor]);
      message.success('因子添加成功');
    }
  };

  const handleRemoveFactor = (factorId) => {
    setSelectedFactors(selectedFactors.filter(f => f.id !== factorId));
    message.success('因子移除成功');
  };

  const handleWeightChange = (factorId, weight) => {
    setSelectedFactors(selectedFactors.map(f => 
      f.id === factorId ? { ...f, customWeight: weight } : f
    ));
  };

  const handleViewFormula = (factor) => {
    Modal.info({
      title: `${factor.name} - 计算公式`,
      width: 600,
      content: (
        <div>
          <p><strong>因子名称：</strong>{factor.name}</p>
          <p><strong>因子类型：</strong>{factor.type}</p>
          <p><strong>因子分类：</strong>{factor.category}</p>
          <p><strong>计算公式：</strong></p>
          <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', fontSize: '14px' }}>
            {factor.formula}
          </pre>
        </div>
      ),
    });
  };

  const handlePreview = async () => {
    try {
      const values = await form.validateFields();
      
      if (selectedFactors.length === 0) {
        message.error('请至少选择一个因子');
        return;
      }

      // 检查权重总和是否为1
      const totalWeight = selectedFactors.reduce((sum, f) => sum + f.customWeight, 0);
      if (Math.abs(totalWeight - 1) > 0.01) {
        message.warning('权重总和应为100%，当前为' + (totalWeight * 100).toFixed(1) + '%');
      }

      const newDerivedFactor = {
        name: values.name,
        description: values.description,
        factors: selectedFactors,
        formula: generateFormula(selectedFactors),
        totalWeight: totalWeight,
        category: values.category,
        businessScenario: values.businessScenario
      };

      setDerivedFactor(newDerivedFactor);
      setIsPreviewModalVisible(true);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const generateFormula = (factors) => {
    const weightedFactors = factors.map(f => 
      `(${f.customWeight} * ${f.name})`
    );
    return `derived_factor = ${weightedFactors.join(' + ')}`;
  };

  const handleSave = () => {
    message.success('衍生因子创建成功');
    setIsPreviewModalVisible(false);
    form.resetFields();
    setSelectedFactors([]);
  };

  const getTotalWeight = () => {
    return selectedFactors.reduce((sum, f) => sum + f.customWeight, 0);
  };

  return (
    <div style={{ padding: '24px' }}>
      <Title level={3}>创建衍生因子</Title>
      <Paragraph type="secondary">
        通过多因子加权方式创建复合衍生因子，支持自定义权重配置和公式生成
      </Paragraph>

      <Row gutter={24}>
        {/* 左侧：基本信息 */}
        <Col span={12}>
          <Card title="基本信息" style={{ marginBottom: '24px' }}>
            <Form
              form={form}
              layout="vertical"
              initialValues={{ category: '复合因子', businessScenario: '量化投研' }}
            >
              <Form.Item
                name="name"
                label="衍生因子名称"
                rules={[{ required: true, message: '请输入衍生因子名称' }]}
              >
                <Input placeholder="请输入衍生因子名称" />
              </Form.Item>

              <Form.Item
                name="category"
                label="因子分类"
                rules={[{ required: true, message: '请选择因子分类' }]}
              >
                <Select placeholder="请选择因子分类">
                  <Option value="复合因子">复合因子</Option>
                  <Option value="技术因子">技术因子</Option>
                  <Option value="基本面因子">基本面因子</Option>
                  <Option value="风险因子">风险因子</Option>
                  <Option value="宏观因子">宏观因子</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="businessScenario"
                label="业务场景"
                rules={[{ required: true, message: '请选择业务场景' }]}
              >
                <Select placeholder="请选择业务场景">
                  <Option value="基金筛选">基金筛选</Option>
                  <Option value="量化投研">量化投研</Option>
                  <Option value="风险管理">风险管理</Option>
                  <Option value="资产配置">资产配置</Option>
                </Select>
              </Form.Item>

              <Form.Item
                name="description"
                label="因子描述"
                rules={[{ required: true, message: '请输入因子描述' }]}
              >
                <TextArea 
                  rows={4}
                  placeholder="请输入衍生因子的详细描述"
                />
              </Form.Item>
            </Form>
          </Card>

          {/* 因子选择 */}
          <Card title="选择基础因子">
            <Form.Item label="添加因子">
              <Select
                placeholder="选择要添加的因子"
                style={{ width: '100%' }}
                onChange={handleAddFactor}
                showSearch
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {availableFactors.map(factor => (
                  <Option key={factor.id} value={factor.id}>
                    {factor.name} - {factor.type}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Alert
              message="操作提示"
              description="从左侧选择基础因子添加到右侧，然后调整各因子的权重。权重总和应为100%。"
              type="info"
              showIcon
              style={{ marginBottom: '16px' }}
            />
          </Card>
        </Col>

        {/* 右侧：因子配置 */}
        <Col span={12}>
          <Card title="因子配置">
            {selectedFactors.length === 0 ? (
              <div style={{ textAlign: 'center', padding: '40px 0', color: '#666' }}>
                <ExperimentOutlined style={{ fontSize: '48px', marginBottom: '16px' }} />
                <p>请从左侧选择基础因子</p>
              </div>
            ) : (
              <>
                <Table
                  dataSource={selectedFactors}
                  columns={columns}
                  rowKey="id"
                  pagination={false}
                  size="small"
                  style={{ marginBottom: '16px' }}
                />

                <Divider />

                {/* 权重调整 */}
                <div style={{ marginBottom: '16px' }}>
                  <h4>权重调整</h4>
                  {selectedFactors.map(factor => (
                    <div key={factor.id} style={{ marginBottom: '12px', display: 'flex', alignItems: 'center' }}>
                      <span style={{ width: '120px', fontSize: '14px' }}>{factor.name}:</span>
                      <InputNumber
                        min={0}
                        max={1}
                        step={0.01}
                        value={factor.customWeight}
                        onChange={(value) => handleWeightChange(factor.id, value)}
                        style={{ width: '120px', marginRight: '8px' }}
                      />
                      <span style={{ color: '#666' }}>{(factor.customWeight * 100).toFixed(1)}%</span>
                    </div>
                  ))}
                </div>

                <Divider />

                {/* 权重统计 */}
                <Row gutter={16} style={{ marginBottom: '16px' }}>
                  <Col span={12}>
                    <Statistic
                      title="权重总和"
                      value={(getTotalWeight() * 100).toFixed(1)}
                      suffix="%"
                      valueStyle={{ 
                        color: Math.abs(getTotalWeight() - 1) < 0.01 ? '#52c41a' : '#faad14' 
                      }}
                    />
                  </Col>
                  <Col span={12}>
                    <Statistic
                      title="因子数量"
                      value={selectedFactors.length}
                      prefix={<CodeOutlined />}
                    />
                  </Col>
                </Row>

                {Math.abs(getTotalWeight() - 1) > 0.01 && (
                  <Alert
                    message="权重警告"
                    description={`权重总和为${(getTotalWeight() * 100).toFixed(1)}%，建议调整为100%`}
                    type="warning"
                    showIcon
                    style={{ marginBottom: '16px' }}
                  />
                )}

                <Space>
                  <Button 
                    type="primary" 
                    icon={<CalculatorOutlined />}
                    onClick={handlePreview}
                  >
                    预览公式
                  </Button>
                  <Button 
                    icon={<SaveOutlined />}
                    onClick={handlePreview}
                  >
                    保存因子
                  </Button>
                </Space>
              </>
            )}
          </Card>
        </Col>
      </Row>

      {/* 预览模态框 */}
      <Modal
        title="衍生因子预览"
        open={isPreviewModalVisible}
        onOk={handleSave}
        onCancel={() => setIsPreviewModalVisible(false)}
        width={800}
        okText="保存因子"
        cancelText="取消"
      >
        {derivedFactor && (
          <div>
            <Row gutter={16}>
              <Col span={12}>
                <Card size="small" title="基本信息">
                  <p><strong>因子名称：</strong>{derivedFactor.name}</p>
                  <p><strong>因子分类：</strong>{derivedFactor.category}</p>
                  <p><strong>业务场景：</strong>{derivedFactor.businessScenario}</p>
                  <p><strong>权重总和：</strong>{(derivedFactor.totalWeight * 100).toFixed(1)}%</p>
                </Card>
              </Col>
              <Col span={12}>
                <Card size="small" title="组成因子">
                  {derivedFactor.factors.map(factor => (
                    <div key={factor.id} style={{ marginBottom: '8px' }}>
                      <span>{factor.name}</span>
                      <span style={{ float: 'right', color: '#666' }}>
                        {(factor.customWeight * 100).toFixed(1)}%
                      </span>
                    </div>
                  ))}
                </Card>
              </Col>
            </Row>

            <Card size="small" title="因子描述" style={{ marginTop: '16px' }}>
              <p>{derivedFactor.description}</p>
            </Card>

            <Card size="small" title="计算公式" style={{ marginTop: '16px' }}>
              <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', fontSize: '14px' }}>
                {derivedFactor.formula}
              </pre>
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default CreateDerivedFactor; 